package com.abso.sunlight.explorer.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.handlers.HandlerUtil;

import com.abso.sunlight.api.Legislator;
import com.abso.sunlight.explorer.SelectionUtils;
import com.abso.sunlight.explorer.editors.LegislatorDetailsEditor;
import com.abso.sunlight.explorer.editors.LegislatorDetailsEditorInput;

/**
 * Shows details of a selected legislator.
 */
public class ShowLegislatorDetailsHandler extends AbstractHandler {

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.core.commands.AbstractHandler#execute(org.eclipse.core.commands.ExecutionEvent)
     */
    public Object execute(ExecutionEvent event) throws ExecutionException {
        ISelection sel = HandlerUtil.getCurrentSelection(event);
        Legislator legislator = SelectionUtils.getSelectedLegislator(sel, true);
        if (legislator != null) {
            try {
                HandlerUtil.getActiveWorkbenchWindow(event).getActivePage().openEditor(new LegislatorDetailsEditorInput(legislator),
                        LegislatorDetailsEditor.ID, true, IWorkbenchPage.MATCH_INPUT);
            } catch (PartInitException e) {
                ErrorDialog.openError(HandlerUtil.getActiveShell(event), "Error", "Unable to open details editor", e.getStatus());
            }

        }
        return null;
    }

}
